import {
    ClassicEditor,
    Autosave,
    Essentials,
    Paragraph,
    Plugin,
    ButtonView,
    Heading,
    List,
    Bold,
    Italic,
    createDropdown,
    addListToDropdown,
    ViewModel,
    Model,
    DropdownPanelView,
    ListView,
    Collection,
    addToolbarToDropdown,
    InputTextView,
    Mention,
    View,
    ViewCollection,
} from "ckeditor5";
import InsertQuoteCommand from "@/components/common/item/ckeditor/command";
import i18n from "@/language";

import mammoth from "mammoth";
const icon = `<svg t="1747962203310" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6802" width="256" height="256"><path d="M667.2 69.12L656 64H293.44a59.68 59.68 0 0 0-64 55.52 75.2 75.2 0 0 0 0 10.4v146.4h-51.52a75.52 75.52 0 0 0-65.76 80v415.04h117.76V960H912V332.96z m-13.76 65.76L827.2 323.52h-144c-14.24 0-33.28-16-33.28-28.16v-160zM160 724.32v-368c0-12.16 4.48-33.12 18.72-33.12H512c14.08 0 23.52 20.96 23.52 33.12v368zM864.96 915.2H276.96v-144h305.76V356.64a77.76 77.76 0 0 0-70.56-80h-235.2V130.08c0-13.92 0-18.88 16-18.88h311.52v184.16a81.76 81.76 0 0 0 80 75.2h177.76v544z" fill="#4B4E54" p-id="6803"></path><path d="M441.44 467.36a21.28 21.28 0 0 0-21.92 20.8 17.44 17.44 0 0 0 0 2.88v126.72l-64-84.64a32 32 0 0 0-44.32-6.08 35.52 35.52 0 0 0-5.92 6.08l-60.48 84.64v-126.72a21.44 21.44 0 0 0-18.88-23.68 14.08 14.08 0 0 0-3.68 0 21.28 21.28 0 0 0-21.92 20.8v171.68a32 32 0 0 0 52.48 23.84L334.4 576l76.32 103.52 4.48 4.96a34.56 34.56 0 0 0 19.52 6.72 48 48 0 0 0 16-2.24 30.72 30.72 0 0 0 17.28-28.32V490.56a28.64 28.64 0 0 0-26.56-23.2z" fill="#4B4E54" p-id="6804"></path></svg>`;

class InsertOptions extends Plugin {
    static get pluginName() {
        return "InsertOptions";
    }
    constructor(editor) {
        super(editor);
        this.editor = editor;
    }
    init() {
        const editor = this.editor;

        const options = editor.config.get("insertOptions") || [];
        const label = editor.config.get("label") || i18n.global.t("public.insert_option");

        editor.commands.add("insertQuote", new InsertQuoteCommand(editor));
        editor.ui.componentFactory.add("insertoptions", (locale) => {
            const dropdown = createDropdown(locale);
            this._setupDropdown(dropdown, options, label);
            return dropdown;
        });
    }
    _setupDropdown(dropdown, options, label) {
        dropdown.buttonView.set({
            withText: true,
            label,
            tooltip: true,
        });

        const items = new Collection();
        options.forEach((opt) => {
            items.add({
                type: "button",
                model: new ViewModel({
                    label: "{" + opt.mappingValue + "}",
                    value: "{" + opt.mappingValue + "}",
                    withText: true,
                }),
            });
        });

        addListToDropdown(dropdown, items);

        const editor = this.editor;        
        const command = editor.commands.get('insertQuote');
        dropdown.bind('isEnabled').to(command, 'isEnabled');
        
        dropdown.on("execute", (evt) => {
            this.editor.execute("insertQuote", evt.source.value);
        });
    }
}

class WordImport extends Plugin {
    static get pluginName() {
        return "WordImport";
    }
    static mode = "view";
    init() {
        console.log("WordImport init");
        WordImport.mode = "view";
        const editor = this.editor;
        // The button must be registered among the UI components of the editor
        // to be displayed in the toolbar.
        editor.ui.componentFactory.add("wordimport", () => {
            // The button will be an instance of ButtonView.
            const button = new ButtonView();
            button.set({
                label: "",
                withText: true,
                icon: icon,
            });
            button.on("execute", () => {
                if (WordImport.mode == "view" || WordImport.mode == "submit") return;
                document.querySelector(".input-group-item input").click();
            });
            return button;
        });
    }
}

// 带搜索的下拉菜单
class SearchDropDown extends Plugin {
    static get pluginName() {
        return "SearchDropDown";
    }
    init() {
        const editor = this.editor;
        const options = editor.config.get("insertOptions") || [];
        const label = editor.config.get("label") || i18n.global.t("public.insert_option");
        const isolationDisabled = editor.config.get("isolationDisabled") || false;
        const templateVariable = editor.config.get("templateVariable") || false;
        editor.commands.add("insertQuote", new InsertQuoteCommand(editor));
        editor.ui.componentFactory.add("searchdropdown", (locale) => {
            const dropdown = createDropdown(locale);
            this._setupDropdown(dropdown, options, label, isolationDisabled, templateVariable);
            return dropdown;
        });
    }
    _setupDropdown(dropdown, options, label, isolationDisabled, templateVariable) {
        dropdown.buttonView.set({
            withText: true,
            label,
            tooltip: true,
        });
        // 创建自定义面板视图
        const panelView = new View();
        panelView.setTemplate({
            tag: "div",
            attributes: {
                class: ["ck-insert-options-panel"],
            },
            children: [
                // 搜索框容器
                {
                    tag: "div",
                    attributes: {
                        class: ["ck-search-input-container"],
                        id: "ck-search-input-container",
                        style: "width: 100%;",
                    },
                    children: [],
                },
            ],
        });
        // 获取面板中的元素
        const searchContainer = panelView.template.children[0];
        const listContainer = panelView.template.children[1];

        // 创建搜索输入框
        const searchInput = new InputTextView();
        searchInput.set({
            placeholder: i18n.global.t("public.keyword_search"),
            id: "editor_search-input",
            style: "width: 100%;",
        });
        // 添加搜索框到容器
        searchContainer.children.push(searchInput);

        // 创建列表项视图集合
        const listItems = new ViewCollection();

        // 初始化所有选项
        const itemsCollection = new Collection();
        const filteredCollection = new Collection();

        options.forEach((opt) => {
            const item = {
                type: "button",
                model: new ViewModel({
                    label: opt.mappingValue + "：" + (opt.mappingOther == "null" || !opt.mappingOther ? i18n.global.t("public.no_explain") : opt.mappingOther),
                    value: templateVariable ? "{" + opt.mappingValue + "}" : opt.mappingValue,
                    description: opt.mappingOther || "",
                    withText: true,
                }),
            };
            itemsCollection.add(item);
            filteredCollection.add(item);
        });

        // 搜索功能
        searchInput.on("input", () => {
            const searchTerm = searchInput.element.value.toLowerCase();
            filteredCollection.clear();

            if (searchTerm) {
                itemsCollection.forEach((item) => {
                    const label = item.model.label.toLowerCase();

                    const description = (item.model.description || "").toLowerCase();
                    if (label.includes(searchTerm) || description.includes(searchTerm)) {
                        filteredCollection.add(item);
                    }
                });
            } else {
                itemsCollection.forEach((item) => filteredCollection.add(item));
            }
        });

        // 设置下拉面板内容
        dropdown.panelView.children.add(panelView);

        addListToDropdown(dropdown, filteredCollection);

        const editor = this.editor;        
        const command = editor.commands.get('insertQuote');
        if(!isolationDisabled) {
            dropdown.bind('isEnabled').to(command, 'isEnabled');
        }

        // 选择事件处理
        dropdown.on("execute", (evt) => {
            this.editor.execute("insertQuote", evt.source.value);
        });
    }
}

export { InsertOptions, WordImport, SearchDropDown };
